package service

import (
	"context"
	"github.com/shopspring/decimal"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"time"
)

type _purchasePlanService struct{}

func (s _purchasePlanService) GetByIdListApi(ctx context.Context, list, statusList []int64) ([]*model.PurchasePlanEntity, error) {
	tx := dao.PurchasePlanEntity.WithContext(ctx).Where(
		dao.PurchasePlanEntity.ID.In(list...),
	)
	if len(statusList) > 0 {
		tx = tx.Where(dao.PurchasePlanEntity.Status.In(statusList...))
	}
	return tx.Find()
}

func (s _purchasePlanService) GetByIdApi(ctx context.Context, id int64) (*model.PurchasePlanEntity, error) {
	return dao.PurchasePlanEntity.WithContext(ctx).Where(
		dao.PurchasePlanEntity.ID.Eq(id),
	).First()

}

func (s _purchasePlanService) ModifyStatusByIdListApi(ctx context.Context, tx *dao.QueryTx, idList []int64, status int64) error {
	if _, err := tx.PurchasePlanEntity.WithContext(ctx).Where(dao.PurchasePlanEntity.ID.In(idList...)).UpdateSimple(
		dao.PurchasePlanEntity.Status.Value(status),
	); err != nil {
		return err
	}
	return nil
}

func (s _purchasePlanService) GetPurchasePlanApi(ctx context.Context, enterpriseID int64, spuId int64, supplierId int64, purchaserId int64, sendGoodsDate time.Time) (*model.PurchasePlanEntity, error) {
	return dao.PurchasePlanEntity.WithContext(ctx).Where(
		dao.PurchasePlanEntity.EnterpriseID.Eq(enterpriseID),
		dao.PurchasePlanEntity.SpuID.Eq(spuId),
		dao.PurchasePlanEntity.SupplierID.Eq(supplierId),
		dao.PurchasePlanEntity.PurchaserID.Eq(purchaserId),
		dao.PurchasePlanEntity.ExpectationGoodsDate.DateFormat("%Y-%m-%d").Eq(sendGoodsDate.Format("2006-01-02")),
	).First()
}

func (s _purchasePlanService) ModifyRequirementsCountByIdApi(ctx context.Context, tx *dao.QueryTx, id int64, count decimal.Decimal) error {
	if _, err := tx.PurchasePlanEntity.WithContext(ctx).Where(dao.PurchasePlanEntity.ID.Eq(id)).UpdateSimple(
		dao.PurchasePlanEntity.RequirementsCount.Value(count),
	); err != nil {
		return err
	}
	return nil
}

func (s _purchasePlanService) CreateApi(ctx context.Context, tx *dao.QueryTx, m *model.PurchasePlanEntity) error {
	if err := tx.PurchasePlanEntity.WithContext(ctx).Create(m); err != nil {
		return err
	}
	return nil
}

func (s _purchasePlanService) GetByOrderDetailIdListApi(ctx context.Context, list []int64) ([]*model.PurchasePlanEntity, error) {
	return dao.PurchasePlanEntity.WithContext(ctx).Where(dao.PurchasePlanEntity.OrdersDetailID.In(list...)).Find()
}

var PurchasePlanService = new(_purchasePlanService)
